<template>
  <div class="sx-statistics-container">
    <!-- 头部信息 -->
    <div class="sx-header-section">
      <div class="sx-title">酸轧厚度与版形分析</div>
      <div class="sx-conditions">
        <el-input v-model="currentRollNo" placeholder="请输入卷号" class="sx-roll-input" />
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="sx-date-picker"
        />
        <el-select v-model="currentTeam" placeholder="选择班组" class="sx-select"
          ><el-option label="甲班" value="甲班" /><el-option label="乙班" value="乙班" /><el-option label="丙班" value="丙班"
        /></el-select>
        <el-select v-model="currentSpec" placeholder="选择品规" class="sx-select"
          ><el-option label="SPHC" value="SPHC" /><el-option label="DC04" value="DC04"
        /></el-select>
        <button class="sx-btn sx-analysis-btn">分析</button>
      </div>
    </div>

    <!-- 主体内容区块 -->
    <div class="sx-main-content">
      <!-- 左侧：多维度分析+趋势图 -->
      <div class="sx-panel sx-left-panel">
        <div class="sx-panel-header">多维度分析</div>
        <div class="sx-panel-body">
          <div ref="bubbleChartRef" class="sx-bubble-chart"></div>
          <div class="sx-panel-subtitle">问题发生率趋势</div>
          <div ref="trendChartRef" class="sx-trend-chart"></div>
        </div>
      </div>
      <!-- 右侧：优化建议+异常列表+根因关系 -->
      <div class="sx-panel sx-right-panel">
        <div class="sx-panel-header">优化建议与异常</div>
        <div class="sx-panel-body sx-panel-body-flex">
          <div class="sx-advise-table-wrap">
            <div class="sx-panel-subtitle">优化建议表</div>
            <el-table :data="adviseTableData" border size="small">
              <el-table-column prop="team" label="班组" width="70" />
              <el-table-column prop="spec" label="品规" width="80" />
              <el-table-column prop="problem" label="问题类型" />
              <el-table-column prop="level" label="等级" width="60" />
              <el-table-column prop="suggest" label="建议" />
              <el-table-column prop="rate" label="发生率" width="70" />
            </el-table>
          </div>
          <div class="sx-abnormal-list-wrap">
            <div class="sx-panel-subtitle">异常列表</div>
            <el-table :data="abnormalListData" border size="small">
              <el-table-column prop="time" label="时间" width="160" />
              <el-table-column prop="handler" label="处理人" width="80" />
              <el-table-column prop="type" label="异常类型" />
              <el-table-column prop="status" label="处理状态" width="90" />
            </el-table>
          </div>
          <div class="sx-root-cause-wrap">
            <div class="sx-panel-subtitle">根因关系</div>
            <div ref="rootCauseChartRef" class="sx-root-cause-chart"></div>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部：问题分布柱状图+热力图 -->
    <div class="sx-bottom-content">
      <div class="sx-panel sx-bottom-panel">
        <div class="sx-panel-header">问题分布</div>
        <div class="sx-panel-body sx-bottom-charts">
          <div ref="issueBarChartRef" class="sx-issue-bar-chart"></div>
          <div ref="issueHeatChartRef" class="sx-issue-heat-chart"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted, nextTick } from 'vue';
  import * as echarts from 'echarts/core';
  import type { EChartsOption } from 'echarts';
  import { ScatterChart, LineChart, BarChart, HeatmapChart, GraphChart } from 'echarts/charts';
  import { TitleComponent, TooltipComponent, GridComponent, LegendComponent, VisualMapComponent } from 'echarts/components';
  import { CanvasRenderer } from 'echarts/renderers';

  echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent,
    VisualMapComponent,
    ScatterChart,
    LineChart,
    BarChart,
    HeatmapChart,
    GraphChart,
    CanvasRenderer,
  ]);

  // 头部条件
  const currentRollNo = ref('L12501197700');
  const dateRange = ref([]);
  const currentTeam = ref('甲班');
  const currentSpec = ref('SPHC');
  // 优化建议表 mock
  const adviseTableData = ref([
    { team: '甲班', spec: 'SPHC', problem: '厚度超差', level: '高', suggest: '调整张力', rate: '1.4%' },
    { team: '乙班', spec: 'DC04', problem: '板形异常', level: '中', suggest: '优化冷却', rate: '1.2%' },
  ]);
  // 异常列表 mock
  const abnormalListData = ref([
    { time: '2024-06-01 08:00', handler: '张三', type: '厚度异常', status: '已处理' },
    { time: '2024-06-01 09:30', handler: '李四', type: '板形异常', status: '未处理' },
  ]);
  // 图表 ref
  const bubbleChartRef = ref<HTMLElement | null>(null);
  const trendChartRef = ref<HTMLElement | null>(null);
  const rootCauseChartRef = ref<HTMLElement | null>(null);
  const issueBarChartRef = ref<HTMLElement | null>(null);
  const issueHeatChartRef = ref<HTMLElement | null>(null);

  // --- ECharts 实例 ---
  let bubbleChartInstance: echarts.ECharts | null = null;
  let trendChartInstance: echarts.ECharts | null = null;
  let rootCauseChartInstance: echarts.ECharts | null = null;
  let issueBarChartInstance: echarts.ECharts | null = null;
  let issueHeatChartInstance: echarts.ECharts | null = null;

  // --- 气泡图 mock 数据 ---
  const bubbleOption: EChartsOption = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'item',
      formatter: (p: any) => `卷号: ${p.data[3]}<br/>厚度偏差: ${p.data[0]}<br/>板形指标: ${p.data[1]}<br/>异常等级: ${p.data[2]}`,
    },
    xAxis: {
      name: '厚度偏差',
      nameTextStyle: { color: '#c0c4cc', fontWeight: 'bold' },
      axisLabel: { color: '#c0c4cc' },
      splitLine: { lineStyle: { color: '#3a5a8a' } },
    },
    yAxis: {
      name: '板形指标',
      nameTextStyle: { color: '#c0c4cc', fontWeight: 'bold' },
      axisLabel: { color: '#c0c4cc' },
      splitLine: { lineStyle: { color: '#3a5a8a' } },
    },
    series: [
      {
        type: 'scatter',
        symbolSize: (d: any) => 18 + d[2] * 6,
        data: [
          [0.12, 1.2, 2, 'L12501197700'],
          [0.18, 1.5, 3, 'L12501197701'],
          [0.09, 1.1, 1, 'L12501197702'],
          [0.22, 1.8, 4, 'L12501197703'],
          [0.15, 1.3, 2, 'L12501197704'],
          [0.19, 1.7, 3, 'L12501197705'],
          [0.11, 1.0, 1, 'L12501197706'],
        ],
        itemStyle: {
          color: (params: any) => {
            const level = params.data[2];
            if (level === 4) return '#ff4d4f';
            if (level === 3) return '#e6a23c';
            if (level === 2) return '#67c23a';
            return '#409eff';
          },
          opacity: 0.85,
        },
        label: { show: true, formatter: (p: any) => p.data[3], color: '#fff', fontSize: 10, position: 'top' },
      },
    ],
  };

  // --- 趋势折线图 mock 数据 ---
  const trendOption: EChartsOption = {
    backgroundColor: 'transparent',
    tooltip: { trigger: 'axis', backgroundColor: 'rgba(10, 26, 58, 0.8)', borderColor: '#3a5a8a', textStyle: { color: '#c0c4cc' } },
    grid: { left: '10%', right: '5%', bottom: '15%', top: '12%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: Array.from({ length: 10 }, (_, i) => `${i + 1}月`),
      axisLine: { lineStyle: { color: '#3a5a8a' } },
      axisLabel: { color: '#c0c4cc', fontSize: 10 },
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#c0c4cc', fontSize: 10, formatter: '{value} %' },
      splitLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.3)' } },
      axisLine: { lineStyle: { color: '#3a5a8a' } },
    },
    series: [
      {
        name: '厚度异常率',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        itemStyle: { color: '#409eff' },
        lineStyle: { width: 2 },
        data: [1.2, 1.1, 1.3, 1.5, 1.4, 1.6, 1.7, 1.3, 1.2, 1.1],
      },
      {
        name: '板形异常率',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        itemStyle: { color: '#e6a23c' },
        lineStyle: { width: 2 },
        data: [0.9, 1.0, 1.2, 1.1, 1.3, 1.2, 1.1, 1.0, 1.1, 1.0],
      },
    ],
  };

  // --- 根因关系图 mock 数据 ---
  const rootCauseOption: EChartsOption = {
    backgroundColor: 'transparent',
    tooltip: {},
    series: [
      {
        type: 'graph',
        layout: 'force',
        roam: true,
        label: { show: true, color: '#fff', fontWeight: 'bold' },
        force: { repulsion: 120, edgeLength: 80 },
        data: [
          { name: '厚度异常', symbolSize: 48, itemStyle: { color: '#409eff' } },
          { name: '张力波动', symbolSize: 32, itemStyle: { color: '#e6a23c' } },
          { name: '温度异常', symbolSize: 32, itemStyle: { color: '#67c23a' } },
          { name: '设备磨损', symbolSize: 32, itemStyle: { color: '#ff4d4f' } },
          { name: '板形异常', symbolSize: 48, itemStyle: { color: '#91cc75' } },
          { name: '冷却不均', symbolSize: 32, itemStyle: { color: '#3ba272' } },
          { name: '轧辊异常', symbolSize: 32, itemStyle: { color: '#fac858' } },
        ],
        links: [
          { source: '厚度异常', target: '张力波动' },
          { source: '厚度异常', target: '温度异常' },
          { source: '厚度异常', target: '设备磨损' },
          { source: '板形异常', target: '冷却不均' },
          { source: '板形异常', target: '轧辊异常' },
          { source: '厚度异常', target: '板形异常' },
        ],
        lineStyle: { color: '#3a5a8a', width: 2 },
        edgeLabel: { show: false },
      },
    ],
  };

  // --- 问题分布柱状图 mock 数据 ---
  const issueBarOption: EChartsOption = {
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      backgroundColor: 'rgba(10, 26, 58, 0.8)',
      borderColor: '#3a5a8a',
      textStyle: { color: '#c0c4cc' },
    },
    grid: { left: '10%', right: '5%', bottom: '15%', top: '12%', containLabel: true },
    xAxis: {
      type: 'category',
      data: ['厚度超差', '板形异常', '边浪', '中浪', '折叠', '划伤'],
      axisLine: { lineStyle: { color: '#3a5a8a' } },
      axisLabel: { color: '#c0c4cc', fontSize: 12 },
    },
    yAxis: {
      type: 'value',
      axisLabel: { color: '#c0c4cc', fontSize: 12, formatter: '{value}' },
      splitLine: { lineStyle: { color: 'rgba(58, 90, 138, 0.3)' } },
      axisLine: { lineStyle: { color: '#3a5a8a' } },
    },
    series: [
      {
        name: '数量',
        type: 'bar',
        barWidth: '50%',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2979ff' },
            { offset: 1, color: '#1c2d5a' },
          ]),
          borderRadius: [3, 3, 0, 0],
        },
        data: [120, 98, 60, 45, 30, 18],
      },
    ],
  };

  // --- 问题热力图 mock 数据 ---
  const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`);
  const days = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  const heatData: [number, number, number][] = [];
  for (let i = 0; i < days.length; i++) {
    for (let j = 0; j < hours.length; j++) {
      heatData.push([j, i, Math.floor(Math.random() * 10)]);
    }
  }
  const issueHeatOption: EChartsOption = {
    backgroundColor: 'transparent',
    tooltip: { position: 'top', formatter: (p: any) => `${days[p.data[1]]} ${hours[p.data[0]]}<br/>异常数: ${p.data[2]}` },
    grid: { left: 60, right: 20, top: 30, bottom: 30 },
    xAxis: {
      type: 'category',
      data: hours,
      splitArea: { show: true },
      axisLabel: { color: '#c0c4cc', fontSize: 10 },
      axisLine: { lineStyle: { color: '#3a5a8a' } },
    },
    yAxis: {
      type: 'category',
      data: days,
      splitArea: { show: true },
      axisLabel: { color: '#c0c4cc', fontSize: 10 },
      axisLine: { lineStyle: { color: '#3a5a8a' } },
    },
    visualMap: {
      min: 0,
      max: 10,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: 5,
      inRange: { color: ['#409eff', '#67c23a', '#e6a23c', '#ff4d4f'] },
      textStyle: { color: '#c0c4cc' },
    },
    series: [
      {
        name: '异常热力',
        type: 'heatmap',
        data: heatData,
        label: { show: false },
        emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.5)' } },
      },
    ],
  };

  // --- 图表初始化与自适应 ---
  const resizeCharts = () => {
    bubbleChartInstance?.resize();
    trendChartInstance?.resize();
    rootCauseChartInstance?.resize();
    issueBarChartInstance?.resize();
    issueHeatChartInstance?.resize();
  };

  const initCharts = () => {
    if (bubbleChartRef.value) {
      bubbleChartInstance = echarts.init(bubbleChartRef.value as HTMLDivElement);
      bubbleChartInstance.setOption(bubbleOption);
    }
    if (trendChartRef.value) {
      trendChartInstance = echarts.init(trendChartRef.value as HTMLDivElement);
      trendChartInstance.setOption(trendOption);
    }
    if (rootCauseChartRef.value) {
      rootCauseChartInstance = echarts.init(rootCauseChartRef.value as HTMLDivElement);
      rootCauseChartInstance.setOption(rootCauseOption);
    }
    if (issueBarChartRef.value) {
      issueBarChartInstance = echarts.init(issueBarChartRef.value as HTMLDivElement);
      issueBarChartInstance.setOption(issueBarOption);
    }
    if (issueHeatChartRef.value) {
      issueHeatChartInstance = echarts.init(issueHeatChartRef.value as HTMLDivElement);
      issueHeatChartInstance.setOption(issueHeatOption);
    }
  };

  onMounted(() => {
    nextTick(() => {
      initCharts();
      window.addEventListener('resize', resizeCharts);
    });
  });
  onUnmounted(() => {
    window.removeEventListener('resize', resizeCharts);
    bubbleChartInstance?.dispose();
    trendChartInstance?.dispose();
    rootCauseChartInstance?.dispose();
    issueBarChartInstance?.dispose();
    issueHeatChartInstance?.dispose();
  });
</script>

<style scoped>
  .sx-statistics-container {
    background: linear-gradient(135deg, #0a1a3a 60%, #142a52 100%);
    color: #c0d6ff;
    padding: 18px 18px 0 18px;
    height: 100vh;
    min-height: 0;
    display: flex;
    flex-direction: column;
    font-family: 'Segoe UI', 'Microsoft YaHei', Arial, sans-serif;
    font-size: 15px;
    letter-spacing: 0.02em;
  }
  .sx-header-section {
    background: linear-gradient(90deg, #1c2d5a 80%, #2979ff22 100%);
    border-radius: 10px;
    padding: 18px 28px 10px 28px;
    margin-bottom: 12px;
    box-shadow:
      0 4px 24px 0 #1c2d5a55,
      0 1.5px 0 #409eff44 inset;
    position: relative;
  }
  .sx-title {
    font-size: 28px;
    font-weight: 900;
    color: #fff;
    margin-bottom: 10px;
    letter-spacing: 0.08em;
    text-shadow:
      0 0 12px #409effcc,
      0 2px 8px #0a1a3a;
  }
  .sx-conditions {
    display: flex;
    gap: 16px;
    align-items: center;
  }
  .sx-roll-input :deep(.el-input__wrapper),
  .sx-date-picker :deep(.el-input__wrapper),
  .sx-select :deep(.el-input__wrapper) {
    background: #142a52 !important;
    border-radius: 6px !important;
    border: 1.5px solid #2979ff55 !important;
    box-shadow: 0 0 0 1.5px #409eff33 inset !important;
    color: #c0d6ff !important;
    height: 38px !important;
    min-height: 38px !important;
  }
  .sx-roll-input :deep(.el-input__inner),
  .sx-date-picker :deep(.el-input__inner),
  .sx-select :deep(.el-input__inner) {
    background: transparent !important;
    color: #c0d6ff !important;
    font-size: 15px !important;
    font-weight: 500;
    letter-spacing: 0.02em;
    height: 36px !important;
    min-height: 36px !important;
  }
  .sx-roll-input :deep(.el-input__inner::placeholder),
  .sx-date-picker :deep(.el-input__inner::placeholder),
  .sx-select :deep(.el-input__inner::placeholder) {
    color: #6fa1e6 !important;
    opacity: 0.7;
  }
  .sx-roll-input,
  .sx-date-picker,
  .sx-select {
    width: 170px;
    background: none;
    border-radius: 6px;
    box-shadow: none;
  }
  .sx-btn.sx-analysis-btn {
    background: linear-gradient(90deg, #2979ff 0%, #00eaff 100%);
    color: #fff;
    border: none;
    border-radius: 6px;
    padding: 0 28px;
    height: 38px;
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
    box-shadow:
      0 0 12px #2979ff55,
      0 2px 8px #0a1a3a;
    transition:
      box-shadow 0.2s,
      background 0.2s;
    line-height: 38px;
    letter-spacing: 0.04em;
  }
  .sx-btn.sx-analysis-btn:hover {
    background: linear-gradient(90deg, #00eaff 0%, #2979ff 100%);
    box-shadow:
      0 0 24px #00eaff99,
      0 2px 8px #0a1a3a;
  }
  .sx-main-content {
    display: flex;
    gap: 18px;
    flex: 1 1 0;
    min-height: 0;
    max-height: 54vh;
  }
  .sx-left-panel {
    flex-basis: 50%;
    display: flex;
    flex-direction: column;
    min-width: 0;
    justify-content: stretch;
  }
  .sx-right-panel {
    flex-basis: 50%;
    display: flex;
    flex-direction: column;
    min-width: 0;
    justify-content: stretch;
  }
  .sx-panel {
    background: linear-gradient(135deg, #1c2d5a 80%, #183153 100%);
    border-radius: 14px;
    display: flex;
    flex-direction: column;
    overflow: auto;
    box-shadow:
      0 0 24px #2979ff22,
      0 2px 8px #0a1a3a;
    border: 1.5px solid #2979ff44;
    position: relative;
  }
  .sx-panel:before {
    content: '';
    position: absolute;
    inset: 0;
    border-radius: 14px;
    pointer-events: none;
    box-shadow:
      0 0 32px 4px #409eff33 inset,
      0 0 0 2px #409eff22 inset;
    z-index: 1;
  }
  .sx-panel-header {
    font-size: 18px;
    font-weight: bold;
    color: #fff;
    background: linear-gradient(90deg, #2979ff22 0%, #1c2d5a 100%);
    padding: 10px 18px 8px 18px;
    border-bottom: 1.5px solid #409eff33;
    letter-spacing: 0.04em;
    z-index: 2;
  }
  .sx-panel-body {
    padding: 10px 12px 8px 12px;
    flex: 1 1 0;
    min-height: 0;
    display: flex;
    flex-direction: column;
    gap: 10px;
    background: linear-gradient(135deg, #142a52 60%, #1c2d5a 100%);
    box-shadow: 0 0 24px #2979ff11 inset;
    z-index: 2;
    overflow-y: auto;
    scrollbar-width: thin;
    scrollbar-color: #409eff #142a52;
  }
  .sx-panel-body-flex {
    display: flex;
    flex-direction: column;
    gap: 10px;
    flex: 1 1 0;
    min-height: 0;
  }
  .sx-panel-subtitle {
    font-size: 15px;
    color: #00eaff;
    margin: 8px 0 6px 0;
    font-weight: bold;
    letter-spacing: 0.03em;
  }
  .sx-bubble-chart {
    width: 100%;
    height: 100%;
    min-height: 220px;
    max-height: 340px;
    background: linear-gradient(135deg, #0a1a3a 60%, #183153 100%);
    border-radius: 10px;
    box-shadow:
      0 0 24px #409eff22 inset,
      0 0 0 2px #409eff22 inset;
  }
  .sx-trend-chart {
    width: 100%;
    height: 100%;
    min-height: 120px;
    max-height: 180px;
    background: linear-gradient(135deg, #0a1a3a 60%, #183153 100%);
    border-radius: 10px;
    box-shadow:
      0 0 24px #409eff22 inset,
      0 0 0 2px #409eff22 inset;
  }
  .sx-advise-table-wrap,
  .sx-abnormal-list-wrap,
  .sx-root-cause-wrap {
    margin-bottom: 6px;
  }
  .sx-root-cause-wrap {
    flex: 1 1 0;
    min-height: 0;
    display: flex;
    flex-direction: column;
  }
  .sx-root-cause-chart {
    width: 100%;
    flex: 1 1 0;
    min-height: 120px;
    max-height: 220px;
    height: 100%;
  }
  .sx-bottom-content {
    margin-top: 10px;
    flex: 1 1 0;
    min-height: 0;
    display: flex;
    flex-direction: column;
  }
  .sx-bottom-panel {
    width: 100%;
    flex: 1 1 0;
    min-height: 0;
    display: flex;
    flex-direction: column;
  }
  .sx-bottom-charts {
    display: flex;
    gap: 18px;
    flex: 1 1 0;
    min-height: 0;
  }
  .sx-issue-bar-chart,
  .sx-issue-heat-chart {
    flex: 1 1 0;
    min-height: 0;
    height: 100%;
    max-height: 100%;
  }
  :deep(.el-table) {
    background: transparent;
    --el-table-border-color: #2979ff33;
    --el-table-header-bg-color: #183153;
    --el-table-header-text-color: #00eaff;
    --el-table-tr-bg-color: #142a52;
    --el-table-row-hover-bg-color: #2979ff22;
    --el-table-text-color: #c0d6ff;
    --el-table-border: 1.5px solid #2979ff33;
    font-size: 15px;
    border-radius: 8px;
    box-shadow: 0 0 12px #2979ff22 inset;
  }
  :deep(.el-table th.el-table__cell) {
    background: var(--el-table-header-bg-color) !important;
    color: var(--el-table-header-text-color);
    padding: 8px 10px !important;
    font-weight: bold;
    border-color: #2979ff33 !important;
    font-size: 15px;
    letter-spacing: 0.03em;
  }
  :deep(.el-table td.el-table__cell) {
    padding: 8px 10px !important;
    border-color: #2979ff33 !important;
    background: #142a52 !important;
    font-size: 15px;
  }
  :deep(.el-table--border .el-table__inner-wrapper::after),
  :deep(.el-table--border::after),
  :deep(.el-table--border::before),
  :deep(.el-table__inner-wrapper::before) {
    background: #2979ff33;
  }
  :deep(.el-table .el-table__cell) {
    text-align: center;
  }
</style>
